package com.ccjq.jq173.shosestore.web.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * describe: 字符编码过滤器
 *
 * @author xugang
 * @date 2019/5/14 16:36
 */
public class CharacterEncodingFilter implements Filter {


    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("=========== CharacterEncodingFilter.init ===========");
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("=========== CharacterEncodingFilter.doFilter ===========");
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        /*
            GET请求乱码解决：
            1、先对参数以 ISO-8895-1 进行解码
            2、然后再以 UTF-8 进行编码

            例：
               String username = req.getParameter("username");
               username = new String(username.getBytes("ISO-8859-1"), "UTF-8");

               或者

               String username = req.getParameter("username");
               username = URLEncoder.encode(username, "ISO-8859-1");  // 先对用户名进行编码
               username = URLDecoder.decode(username, "UTF-8");       // 再进行utf-8解码

            注：
               GET请求乱码解决应该放在具体的Servlet类中，不适合放在 Filter 中解决
         */

        // POST请求乱码解决
        req.setCharacterEncoding("UTF-8");

        // 设置服务器输出的编码为UTF-8
        resp.setCharacterEncoding("UTF-8");

        //告诉浏览器输出的内容是html,并且以utf-8的编码来查看这个内容。
        resp.setContentType("text/html;charset=utf-8");


        chain.doFilter(req, resp);
    }

    public void destroy() {
        System.out.println("=========== CharacterEncodingFilter.destroy ===========");
    }
}
